<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :inline="true"
      :rules="formRules"
      label-width="140px"
    >
      <el-form-item label="公司名称" prop="name">
        <el-input class="w240" v-model="formData.name" placeholder="请输入公司名称" />
      </el-form-item>
      <el-form-item label="所在地区" prop="areaId">
        <el-tree-select
          class="w240"
          v-model="formData.receiverAreaId"
          :data="areaList"
          :props="defaultProps"
          :render-after-expand="true"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input class="w240" v-model="formData.address" placeholder="请输入公司详细地址" />
      </el-form-item>
      <el-form-item label="法人代表" prop="corporation">
        <el-input class="w240" v-model="formData.corporation" placeholder="请输入法人代表" />
      </el-form-item>
      <el-form-item label="管理员账号" prop="account">
        <el-input class="w240" v-model="formData.account" placeholder="请输入管理员账号" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input class="w240" v-model="formData.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="公司套餐" prop="setmenu">
        <el-select class="w240" v-model="formData.setmenu" clearable placeholder="请选择公司套餐">
          <el-option
            v-for="item in packageList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item  label="创建管理员账号" >
        <div>
          <el-radio-group v-model="formData.radio">
          <el-radio :value="1">是</el-radio>
          <el-radio :value="2">否</el-radio>
        </el-radio-group>
          <!-- <el-input class="w240" v-model="formData.username" placeholder="请输入管理员账号" /> -->
          <div class="el-form-item__error help">开通后自动创建管理员账号，角色为公司管理员</div>
        </div>
      </el-form-item>
      <el-form-item label="账号初始密码" prop="password">
        <el-input class="w240" v-model="formData.password" placeholder="请输入账号初始密码" />
      </el-form-item>
      <el-divider />
      <el-form-item label="营业执照上传" prop="imgUrl">
        <div class="w240">
          <UploadImgs
            v-model="formData.imgUrl"
            :limit="2"
            draggable="false"
            height="150px"
            width="150px"
            class="min-w-80px"
          />
        </div>
      </el-form-item>
      <el-form-item label="办公场所上传" prop="imgUrl2">
        <div class="w240">
          <UploadImgs
            v-model="formData.imgUrl2"
            draggable="false"
            :limit="5"
            height="150px"
            width="150px"
            class="min-w-80px"
          />
        </div>
      </el-form-item>
      <el-form-item label="公司注册年份" prop="registrationTime">
        <el-select class="w240" v-model="formData.registrationTime" clearable placeholder="请选择公司注册年份">
          <el-option
            v-for="item in packageList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as TenantApi from '@/api/system/tenant'
import { CommonStatusEnum } from '@/utils/constants'
import * as TenantPackageApi from '@/api/system/tenantPackage'
import { getAreaTree } from '@/api/system/area'
import { defaultProps } from '@/utils/tree'

defineOptions({ name: 'SystemTenantForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  receiverAreaId:undefined,
  name: undefined,
  packageId: undefined,
  contactName: undefined,
  contactMobile: undefined,
  accountCount: undefined,
  expireTime: undefined,
  website: undefined,
  status: CommonStatusEnum.ENABLE,
  imgUrl:"",
  radio:1,
  // 新增专属
  username: undefined,
  password: undefined
})

// 自定义校验 开始
const validatePass = (rule: any, value: any, callback: any) => {
  let pattern_En = new RegExp("[A-Za-z]")
  if ((pattern_En.test(value))) {
    callback()
  } else {
    callback(new Error("公司名称必须为英文!"))
  }
}
// 自定义校验 结束
const areaList = ref([]) // 地区列表
const formRules = reactive({
  name: [
    { required: true, message: '公司名称不能为空', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  areaId: [{ required: true, message: '所在地区不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
  corporation: [{ required: true, message: '法人代表不能为空', trigger: 'blur' }],
  account: [{ required: true, message: '管理员账号不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
  setmenu: [{ required: true, message: '公司套餐不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '账号初始密码不能为空', trigger: 'blur' }],
  imgUrl:[{ required: true, message: '营业执照不能为空', trigger: 'blur' }],
  imgUrl2:[{ required: true, message: '办公场所不能为空', trigger: 'blur' }],
  registrationTime: [{ required: true, message: '公司注册年份不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const packageList = ref([] as TenantPackageApi.TenantPackageVO[]) // 租户套餐

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TenantApi.getTenant(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载套餐列表
  packageList.value = await TenantPackageApi.getTenantPackageList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TenantApi.TenantVO
    if (formType.value === 'create') {
      await TenantApi.createTenant(data)
      message.success(t('common.createSuccess'))
    } else {
      await TenantApi.updateTenant(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    packageId: undefined,
    contactName: undefined,
    contactMobile: undefined,
    accountCount: undefined,
    expireTime: undefined,
    website: undefined,
    status: CommonStatusEnum.ENABLE,
    username: undefined,
    password: undefined,
    imgUrl:"",
    radio:1,
  }
  formRef.value?.resetFields()
}
onMounted(async () => {
  // 获得地区列表
  areaList.value = await getAreaTree()
})
</script>


<style >
  .help{
    color: #808080;
    width: 240px;
    font-size: 10px;
    word-wrap:break-word; 
    word-break:break-all; 
    overflow: hidden;/*这个参数根据需求来决定要不要*/
  }
</style>
